import { orderType } from "@/type/coffeeType";
import { Button, Card } from "antd";
import React, { FC, memo, ReactNode, useState } from "react";
import { CoffeeCardWrapper } from "./style";

import CarSelect from "../../carSelect";
import { useDispatch } from "react-redux";
import { changeRemoveOrderList } from "@/store/modules/coffeeOrder";
import { orderNum } from "@/utils/orderNum";

interface IProps {
  children?: ReactNode;
  item: orderType[];
  index: number; // order.index
  orderNumber: number;
  time: string;
}

const CoffeeCard: FC<IProps> = memo((props) => {
  const { item, index, orderNumber, time } = props;

  const dispatch = useDispatch();

  // 计算总咖啡杯数
  const coffeeCount = () => {
    let allCount = 0;
    item.forEach((item) => {
      allCount += item.count;
    });
    return allCount;
  };

  // 计算总价格
  const allPrice = () => {
    let allPrice = 0;
    item.forEach((item) => {
      const unitPrice: number = item.count * item.price;
      allPrice += unitPrice;
    });
    return allPrice;
  };

  const [isShowFinish, setIsShowFinish] = useState(false);

  const cardClick = () => {
    setIsShowFinish(true);
  };

  const back = () => {
    setIsShowFinish(false);
  };

  const finish = () => {
    setIsShowFinish(false);
    dispatch(changeRemoveOrderList(index));
  };

  return (
    <CoffeeCardWrapper showFinish={isShowFinish}>
      <Card
        className="card"
        title={`咖啡共 ${coffeeCount()} 杯`}
        extra={orderNum(orderNumber)}
        headStyle={{
          borderBottom: " 1px solid #000",
        }}
        bodyStyle={{
          padding: "10px 24px",
        }}
        onClick={() => cardClick()}
      >
        <div className="content">
          {item &&
            item.map((item, index) => {
              return (
                <div key={index}>
                  <CarSelect item={item} showMore={false} />
                </div>
              );
            })}
        </div>
        <div className="time-price">
          <div className="time">{time}</div>
          <div className="price">￥ {allPrice()}</div>
        </div>
      </Card>
      {isShowFinish && (
        <div className="finish">
          <Button className="backBtn" onClick={() => back()}>
            返回
          </Button>
          <Button className="finishBtn" onClick={() => finish()}>
            出单
          </Button>
        </div>
      )}
    </CoffeeCardWrapper>
  );
});

export default CoffeeCard;
